package com.jwt.controller;

import com.jwt.bean.User;

import com.jwt.util.JwtUtil;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;


@RestController
@RequestMapping("/jwt")
@CrossOrigin("http://127.0.0.1:5500")
public class JwtController {
    /**
     * 登录成功后把user信息，放到payload里面创建token，传递给前端，存到localStorage内，
     * 方便以后每次请求都带上token，实现在线认证
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Map<String,Object> login(User user){
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (user.getUsername().equals("")||user.getPassword().equals("")){
            map.put("msg","账号或者密码为空");
            return map;
        }
        if ("lcq".equals(user.getUsername())&&"lcq".equals(user.getPassword())){
            String token = JwtUtil.generateToken(user);
            map.put("token",token);
            return map;
        }
        map.put("code","400");
        return map;
    }
    /**
     * 获取前端传递的token
     * @param token
     * @return
     */
    @PostMapping("/getWebToken")
    public Map<String,Object> getWebToken(String token, HttpServletRequest request){
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        System.out.println("前端传递的token="+token);
        String requestHeader = request.getHeader("Authorization");
        System.out.println("前端通过请求头传递的token="+requestHeader);
        if ("".equals(token)){
            //获取失败
            map.put("status","400");
            return map;
        }
        //获取成功
        map.put("status","200");
        return map;
    }
}
